/**
 * Created by HP on 2017/10/17.
 */
var mongoose = require('mongoose');
var async = require('async');
//引入数据模型
const DataModel = require('../models/news.model');
const Comment = require('../models/commemt.model');

//增删改查
//增加
exports.create = function (req,res,next) {
	console.log(req.body);
	const  dataModel = new DataModel(req.body);
	//
	
	dataModel.save()
		.then(data=>{
			res.json(data);
		})
	
}
//获取一条
exports.get = function (req,res,next) {
	var id = req.params.id;
	DataModel.findById(id, function (err, data) {
		res.json(data);
	})
}

//修改
exports.update = function (req,res,next) {
	var id = req.params.id;
	DataModel.findByIdAndUpdate(id, {$set:req.body}, {new:false})
		.then(data=>{
			res.json(data)
		})
}

//删除
exports.remove = function (req,res,next) {
	const id = req.params.id;
	DataModel.findByIdAndRemove(id,function (err,data) {
		res.json(data);
	})
}
//分页查询
exports.list = function (req,res,next) {
	var page = (req.body.page)?req.body.page:1;
	var rows = (req.body.rows)?req.body.rows:10;
	// console.log(rows);
	var queryCondition={}//查询条件
	
	if(req.body.title && req.body.title.trim().length>0){
		title = req.body.title;
		queryCondition={
			"title":new RegExp(title,'i'),//正则匹配
			// "press":new RegExp(title,'i')
		}
		// queryCondition2 = {"press":new RegExp(title,'i')}
		// queryCondition =Object.assign(queryCondition1,queryCondition2);
		console.log(queryCondition);
	}
	
	
	//cateId 要精确搜索
	if(req.body.cateId && req.body.cateId.length>0){
		
		console.log(req.body);
		cateId = JSON.parse(req.body.cateId);
		console.log(234);
		console.log(cateId);
		var cateIds = [];
		for(var i=0;i<cateId.length;i++){
			cateIds.push(mongoose.Types.ObjectId(cateId[i]));
		}
		// console.log(cateIds);
		queryCondition={cateId: {$in:cateIds}}
	}
	
	// console.log(queryCondition);
	// console.log(queryCondition)
	// console.log({page:page,limit:limit});
	DataModel.paginate(queryCondition, {sort: { _id: -1 }, page: parseInt(page), limit: parseInt(rows) }, function(err, result) {
		
		async.map(result.docs, function (news,done) {
			console.log(news);
			Comment.count({cateId:news._id},function (err,count) {
				if(err){
					return err;
				}else{
					news.commentCount = count;
					done();
				}
			})
		}, function(err) {
			result.rows = result.docs;
			delete result.docs;
			res.json(result);
		});
		
	});
	
}




//删除多个
exports.deletes = function (req,res,next) {
	var ids = req.body.ids; //字符串
	console.log(ids.split(',').length>0);
	if(ids.length>0){
		DataModel.remove({_id:{$in:ids.split(',')}})
			.then(data=>{
				res.json({"msg":"deletes success","status":200});
			})
	}else{
		res.json({"msg":"deletes fail","status":404});
	}
}